package com.spirngboot.middleware.middleware_rabbitmq.server.rabbitmq.topics;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.spirngboot.middleware.middleware_rabbitmq.server.rabbitmq.simple.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

public class Consumer {
    private static final Logger log = LoggerFactory.getLogger(Producer.class);

    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //1.创建连接工厂
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("120.24.87.40");
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("root");
            connectionFactory.setPassword("Guet@207");
            connectionFactory.setVirtualHost("/");

            Connection connection = null;
            Channel channel = null;
            final String queueName = Thread.currentThread().getName();
            try {
                //2.创建连接Connection
                String connectName = "消费者";
                connection = connectionFactory.newConnection(connectName);
                log.info("创建连接成功,连接名:{},连接:{}", connectName, connection.toString());
                //3.通过连接获取通道Channel
                channel = connection.createChannel();
                log.info("创建通道成功,通道名:{}", channel.toString());
                //4.通过创建交换机,声明队列,绑定关系,路由key,发送信息和接收信息
                channel.basicConsume(queueName, true,
                        (consumerTag, message) -> log.info("{}收到的消息是{}", Thread.currentThread().getName(), new String(message.getBody(), StandardCharsets.UTF_8)),
                        consumerTag -> log.warn("接收消息失败")
                );
                Thread.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //7.关闭通道
                if (channel != null && channel.isOpen()) {
                    try {
                        channel.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //8.关闭连接
                if (connection != null && connection.isOpen()) {
                    try {
                        connection.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    public static void main(String[] args) {
        new Thread(runnable, "queue-topic1").start();
        new Thread(runnable, "queue-topic2").start();
        new Thread(runnable, "queue-topic3").start();
    }
}
